#include "common.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
	int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sock_fd < 0)
		err_sys("socket error\n");

	struct sockaddr_in my_addr;
	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(9999);
	//my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	inet_pton(AF_INET, "127.0.0.1", &my_addr.sin_addr);

	int ret = bind(sock_fd, (struct sockaddr *)&my_addr, sizeof(my_addr));
	if(ret != 0)
		err_sys("bind error\n");

	printf("receive ...\n");
	while(1)
	{
		int recv_len;
		struct sockaddr_in client_addr;
		char buffer[1024] = {0};
		char client_ip[INET_ADDRSTRLEN] = {0};
		socklen_t client_len = sizeof(client_addr);

		recv_len = recvfrom(sock_fd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, &client_len);
		inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, INET_ADDRSTRLEN);
		printf("Client IP : %s\nPort : %d\n", client_ip, ntohs(client_addr.sin_port));
		printf("Recieve data(%d) : %s\n", recv_len, buffer);
	}

	close(sock_fd);

	return 0;
}
